package yns.properties;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class PropertiesHelper {
	public static final String UTF8 = "UTF-8";
	public static final String GBK = "GBK";
	
	private Properties properties;
	
	public PropertiesHelper(FileInputStream fileInputStream) throws FileNotFoundException, IOException {
		properties = new Properties();
		properties.load(fileInputStream);
	}
	
	public PropertiesHelper(InputStream inputStream) throws IOException {
		properties = new Properties();
		properties.load(inputStream);
	}
	

	public PropertiesHelper(String filePath) throws FileNotFoundException, IOException {
		buildProperties(filePath,null);
	}
	
	public PropertiesHelper(String filePath,String charSet) throws FileNotFoundException, IOException {		
		buildProperties(filePath,charSet);
	}
	
	public PropertiesHelper(Class<?> classObj, String relativePath,String charSet) throws IOException {
		String filePath = classObj.getClassLoader().getResource("").getPath()+ relativePath;
		buildProperties(filePath,charSet);
	}
	
	public PropertiesHelper(Class<?> classObj, String relativePath) throws IOException {
		String filePath = classObj.getClassLoader().getResource("").getPath()+ relativePath;
		buildProperties(filePath,null);
	}
	
	private void buildProperties(String filePath,String charSet)  throws IOException {
		properties = new Properties();

		if (charSet == null || "".equals(charSet)) {
			charSet = UTF8;
		}

		InputStream in = null;
		BufferedReader bf = null;
		try {
			
			in = new FileInputStream(filePath);
			bf = new BufferedReader(new InputStreamReader(in, charSet));
			properties.load(bf);
			
		} catch (FileNotFoundException e) {
			throw e;
		} catch (UnsupportedEncodingException e) {
			throw e;
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (bf != null) {
					bf.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	
	public String getValue(String key){
		return properties.getProperty(key);
	}
	
}
